package com.pri.chat.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.style.PictureWindowAnimationStyle;
import com.netease.nim.uikit.net.SharedHelper;
import com.netease.nim.uikit.net.entity.BaseBean;
import com.netease.nim.uikit.net.rxjava.HttpMethods;
import com.netease.nim.uikit.net.subscribers.ProgressSubscriber;
import com.netease.nim.uikit.net.subscribers.SubscriberOnNextListener;
import com.pri.chat.R;
import com.pri.chat.adapter.GridImageAdapter;
import com.pri.chat.event.EventTag;
import com.pri.chat.event.MessageEvent;
import com.pri.chat.utils.Auth;
import com.pri.chat.utils.Des3Util;
import com.pri.chat.utils.FullyGridLayoutManager;
import com.pri.chat.utils.GlideEngine;
import com.pri.chat.utils.bars.StatusBarUtil;
import com.qiniu.android.storage.UploadManager;
import com.vondear.rxtool.view.RxToast;
import com.vondear.rxui.view.dialog.RxDialogLoading;
import com.vondear.rxui.view.progressing.SpriteFactory;
import com.vondear.rxui.view.progressing.Style;
import com.vondear.rxui.view.progressing.sprite.Sprite;

import org.greenrobot.eventbus.EventBus;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 描述：添加类的描述
 *
 * @author wx5e48d604c2885118
 * @time 2020/4/8
 */
public class ReleaseJuBaoAcctivity extends AppCompatActivity {
    @BindView(R.id.et_content)
    EditText etContent;
    @BindView(R.id.rec_img)
    RecyclerView recImg;
    @BindView(R.id.tv_release)
    TextView tvRelease;



    @BindView(R.id.jblxLinear0)
    View jblxLinear0;
    @BindView(R.id.jblxImg0)
    ImageView jblxImg0;
    @BindView(R.id.jblxLinear1)
    View jblxLinear1;
    @BindView(R.id.jblxImg1)
    ImageView jblxImg1;
    @BindView(R.id.jblxLinear2)
    View jblxLinear2;
    @BindView(R.id.jblxImg2)
    ImageView jblxImg2;
    @BindView(R.id.jblxLinear3)
    View jblxLinear3;
    @BindView(R.id.jblxImg3)
    ImageView jblxImg3;
    @BindView(R.id.jblxLinear4)
    View jblxLinear4;
    @BindView(R.id.jblxImg4)
    ImageView jblxImg4;
    @BindView(R.id.jblxLinear5)
    View jblxLinear5;
    @BindView(R.id.jblxImg5)
    ImageView jblxImg5;


    List<View> jblxLinearList = new ArrayList<>();
    List<ImageView> jblxImgList = new ArrayList<>();
    private String[] lxArgs = {"低俗色情","广告","涉政","违法诈骗","诋毁侮辱","其他"};

    private Activity activity;
    private Context context;
    /**
     * 图纸图片
     */
    private GridImageAdapter mPostAdapter;
    private List<LocalMedia> localMediaList = new ArrayList<>();//个人荣誉
    private GridImageAdapter.onAddPicClickListener onAddPicClickListener = () -> {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .setPictureWindowAnimationStyle(new PictureWindowAnimationStyle())// 自定义相册启动退出动画
                .loadImageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项   参考Demo MainActivity中代码
                //   .isOriginalImageControl(cb_original.isChecked())// 是否显示原图控制按钮，如果用户勾选了 压缩、裁剪功能将会失效
                .isWeChatStyle(true)// 是否开启微信图片选择风格，此开关开启了才可使用微信主题！！！
                .isAndroidQTransform(true)// 是否需要处理Android Q 拷贝至应用沙盒的操作，只针对compress(false); && enableCrop(false);有效
                .maxSelectNum(3)// 最大图片选择数量 int
                .minSelectNum(1)// 最小选择数量 int
                .imageSpanCount(3)// 每行显示个数 int
                .isNotPreviewDownload(true)// 预览图片长按是否可以下载
                .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .queryMaxFileSize(50)// 只查多少M以内的图片、视频、音频  单位M
                //   .querySpecifiedFormatSuffix(PictureMimeType.ofPNG())// 查询指定后缀格式资源
                //   .cameraFileName("test.png") // 重命名拍照文件名、注意这个只在使用相机时可以使用
                //   .renameCompressFile("test.png")// 重命名压缩文件名、 注意这个不要重复，只适用于单张图压缩使用
                //   .renameCropFileName("test.png")// 重命名裁剪文件名、 注意这个不要重复，只适用于单张图裁剪使用
                //   .isSingleDirectReturn(false)// 单选模式下是否直接返回，PictureConfig.SINGLE模式下有效
                .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                .previewImage(true)// 是否可预览图片 true or false
                .isCamera(true)// 是否显示拍照按钮 true or false
                .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                .setOutputCameraPath("/CustomPath")// 自定义拍照保存路径,可不填
                .enableCrop(false)// 是否裁剪 true or false
                .compress(true)// 是否压缩 true or false
                .isGif(true)// 是否显示gif图片 true or false
                //   .compressSavePath(getPath())//压缩图片保存地址
                .openClickSound(false)// 是否开启点击声音 true or false
                .selectionMedia(localMediaList)// 是否传入已选图片 List<LocalMedia> list
                .cutOutQuality(90)// 裁剪输出质量 默认100
                .minimumCompressSize(100)// 小于100kb的图片不压缩
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
    };

    private String id;
    private String type;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_release_xinlu_layout);
        StatusBarUtil.setStatusBarMode(this, true, R.color.white);
        activity = this;
        context = this;
        id = getIntent().getExtras().getString("id");
        type = getIntent().getExtras().getString("type");
        ButterKnife.bind(this);
        tvRelease.setText("保存");
        initView();
    }

    private void initView() {
        jblxLinearList.add(jblxLinear0);
        jblxLinearList.add(jblxLinear1);
        jblxLinearList.add(jblxLinear2);
        jblxLinearList.add(jblxLinear3);
        jblxLinearList.add(jblxLinear4);
        jblxLinearList.add(jblxLinear5);


        jblxImgList.add(jblxImg0);
        jblxImgList.add(jblxImg1);
        jblxImgList.add(jblxImg2);
        jblxImgList.add(jblxImg3);
        jblxImgList.add(jblxImg4);
        jblxImgList.add(jblxImg5);


        initImg();
        initLoadingDialog();
    }

    private void initImg() {
        FullyGridLayoutManager manager = new FullyGridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false);
        recImg.setLayoutManager(manager);
        mPostAdapter = new GridImageAdapter(this, onAddPicClickListener);
        mPostAdapter.setList(localMediaList);
        mPostAdapter.setSelectMax(9);
        recImg.setAdapter(mPostAdapter);
        mPostAdapter.setOnItemClickListener((position, v) ->
                PictureSelector.create(this)
                        .themeStyle(R.style.picture_default_style)
                        .loadImageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项
                        .openExternalPreview(position, localMediaList));

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case PictureConfig.CHOOSE_REQUEST:
                // 图片选择结果回调
                if (!PictureSelector.obtainMultipleResult(data).isEmpty()) {
                    localMediaList.clear();
                    localMediaList.addAll(PictureSelector.obtainMultipleResult(data));
                    mPostAdapter.notifyDataSetChanged();
                }
                break;

        }
    }


    private static final String TAG = "ReleaseDTActivity";
    private UploadManager uploadManager = new UploadManager();

    private void uploadImg(String data, int i) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String key = "img_" + i + sdf.format(new Date());
        String token = "ayjstx";
        uploadManager.put(data, key, Auth.create(HttpMethods.ACCESS_KEY, HttpMethods.SECRET_KEY).uploadToken(token),
                (key1, info, res) -> {
                    //res包含hash、key等信息，具体字段取决于上传策略的设置
                    if (info.isOK()) {
                        Log.i("qiniu", "Upload Success");
                        Log.d(TAG, "complete: " + HttpMethods.QN_PATH + key1);
                        if (i == 0) {
                            mImgPath = HttpMethods.QN_PATH + key1;
                        } else {
                            mImgPath = mImgPath + "," + HttpMethods.QN_PATH + key1;
                        }
                        if (i == localMediaList.size() - 1) {
                            rxDialogLoading.dismiss();
                            httpReleaseJuBao();
                        } else {
                            uploadImg(localMediaList.get(i + 1).getCompressPath(), i + 1);
                        }

                    } else {
                        Log.i("qiniu", "Upload Fail");
                    }
                    Log.i("qiniu", key1 + ",\r\n " + info + ",\r\n " + res);
                }, null);
    }

    private RxDialogLoading rxDialogLoading;

    private void initLoadingDialog() {
        rxDialogLoading = new RxDialogLoading(this);
        Sprite sprite = SpriteFactory.create(Style.THREE_BOUNCE);//设置style
        rxDialogLoading.getLoadingView().setIndeterminateDrawable(sprite);
        rxDialogLoading.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        rxDialogLoading.setCancelable(false);//设置是否可取消
    }

    private String mImgPath = "";
    private int selectLxIndex = -1;
    @OnClick({R.id.iv_back, R.id.tv_release,R.id.jblxLinear0,R.id.jblxLinear1,R.id.jblxLinear2,R.id.jblxLinear3,R.id.jblxLinear4,R.id.jblxLinear5})
    public void onViewClicked(View view) {
        if (R.id.tv_release == view.getId()) {
            if ("".equals(etContent.getText().toString())) {
                RxToast.normal("请输入举报内容");
                return;
            }
            if (!localMediaList.isEmpty()) {
                rxDialogLoading.show();
                uploadImg(localMediaList.get(0).getCompressPath(), 0);
            } else {
                httpReleaseJuBao();
            }
        } else if (view.getId() == R.id.iv_back) {
            finish();
        } else {
            for(int i=0;i<jblxLinearList.size();i++){
                if(view == jblxLinearList.get(i)){
                    jblxImgList.get(i).setImageResource(R.mipmap.ic_danxuan_select);
                    selectLxIndex = i;
                }else{
                    jblxImgList.get(i).setImageResource(R.mipmap.ic_danxuan_normal);
                }
            }
        }
    }

    private void httpReleaseJuBao() {
        SubscriberOnNextListener<BaseBean> onNextListener = baseBean -> {
            RxToast.normal("举报成功！");
            MessageEvent messageEvent = new MessageEvent(EventTag.WISH, "");
            EventBus.getDefault().post(messageEvent);
            finish();
        };
        Map<String,Object> params = new HashMap<>();
        params.put("memberId", SharedHelper.readId(this));
        params.put("objId", id);
        params.put("type", type);
        params.put("jbType", lxArgs[selectLxIndex]);
        params.put("content", etContent.getText().toString());
        params.put("picList", mImgPath+"");
        Gson gson = new Gson();
        String s = gson.toJson(params);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(params));
        HttpMethods.getInstance().saveJuBao(new ProgressSubscriber<>(onNextListener, this, true), requestBody);
    }
}
